package com.example.aihub.controller;

import com.example.aihub.dto.ApiResponse;
import com.example.aihub.dto.PostDTO;
import com.example.aihub.entity.Post;
import com.example.aihub.entity.PostCategory;
import com.example.aihub.entity.User;
import com.example.aihub.exception.ResourceNotFoundException;
import com.example.aihub.service.FileUploadService;
import com.example.aihub.service.PostService;
import com.example.aihub.service.UserService;
import com.example.aihub.util.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api/posts")
public class PostController {

    private final PostService postService;
    private final UserService userService;
    private final FileUploadService fileUploadService;

    @Autowired
    public PostController(PostService postService, UserService userService, FileUploadService fileUploadService) {
        this.postService = postService;
        this.userService = userService;
        this.fileUploadService = fileUploadService;
    }

    // 更新创建帖子的方法，支持视频文件和多图片上传
    @PostMapping(consumes = {"multipart/form-data"})
    public ResponseEntity<?> createPost(
            @RequestPart("post") Post post,
            @RequestPart(value = "video", required = false) MultipartFile video,
            @RequestPart(value = "thumbnail", required = false) MultipartFile thumbnail,
            @RequestPart(value = "images", required = false) List<MultipartFile> images) {
        // 获取当前登录用户
        String username = ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
        User user = userService.findByUsername(username)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在: " + username));

        // 设置用户和时间，不再硬编码设置状态，保留前端传来的值
        post.setUser(user);
        post.setCreatedAt(LocalDateTime.now());
        post.setUpdatedAt(LocalDateTime.now());

        // 处理视频文件上传
        if (video != null && !video.isEmpty()) {
            try {
                String videoPath = fileUploadService.uploadFile(video);
                post.setVideoUrl(videoPath);
                
                // 如果没有提供缩略图，则使用视频的默认封面
                if (thumbnail != null && !thumbnail.isEmpty()) {
                    String thumbnailPath = fileUploadService.uploadFile(thumbnail);
                    post.setVideoThumbnailUrl(thumbnailPath);
                } else {
                    // 简化处理，直接使用视频URL作为封面URL
                    post.setVideoThumbnailUrl(videoPath);
                }
            } catch (IOException e) {
                return new ResponseEntity<>(new ApiResponse(false, "视频上传失败: " + e.getMessage(), null), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } else if (images != null && !images.isEmpty()) {
            // 处理图片上传（目前只保存第一张图片作为封面）
            try {
                String imagePath = fileUploadService.uploadFile(images.get(0));
                post.setCoverImageUrl(imagePath);
                
                // 实际项目中可能需要处理多张图片
                // 可以将图片URL保存到一个单独的表中，或者以逗号分隔的字符串保存到post表中
            } catch (IOException e) {
                return new ResponseEntity<>(new ApiResponse(false, "图片上传失败: " + e.getMessage(), null), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }

        Post createdPost = postService.createPost(post);
        PostDTO postDTO = ModelMapper.mapPostToDTO(createdPost);
        return new ResponseEntity<>(new ApiResponse(true, "创建帖子成功", postDTO), HttpStatus.CREATED);
    }

    // 为了兼容原有的JSON请求，保留原来的方法但添加required=false
    @PostMapping(consumes = {"application/json"})
    public ResponseEntity<?> createPostWithJson(@RequestBody Post post) {
        // 复用上面的逻辑
        return createPost(post, null, null, null);
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getPostById(@PathVariable Long id) {
        Post post = postService.getPostById(id)
                .orElseThrow(() -> new ResourceNotFoundException("帖子不存在: " + id));
        // 增加浏览量
        postService.incrementViewCount(post.getId());
        PostDTO postDTO = ModelMapper.mapPostToDTO(post);
        return ResponseEntity.ok(new ApiResponse(true, "获取帖子成功", postDTO));
    }

    // 获取所有帖子，支持分页
    @GetMapping
    public ResponseEntity<?> getAllPosts(@RequestParam(defaultValue = "0") int page, 
                                         @RequestParam(defaultValue = "10") int size) {
        List<Post> posts = postService.getAllPosts(page, size);
        List<PostDTO> postDTOs = posts.stream()
                .map(ModelMapper::mapPostToDTO)
                .toList();
        return ResponseEntity.ok(new ApiResponse(true, "获取帖子列表成功", postDTOs));
    }

    // 添加按分类获取帖子的API
    // 获取特定分类下的已发布帖子，支持分页
    @GetMapping("/category/{category}")
    public ResponseEntity<?> getPostsByCategory(
            @PathVariable String category, 
            @RequestParam(defaultValue = "0") int page, 
            @RequestParam(defaultValue = "10") int size) {
        try {
            // 将字符串转换为PostCategory枚举
            PostCategory postCategory = PostCategory.valueOf(category.toUpperCase());
            
            // 获取特定分类下的已发布帖子
            List<Post> posts = postService.getPublishedPostsByCategory(postCategory, page, size);
            List<PostDTO> postDTOs = posts.stream()
                    .map(ModelMapper::mapPostToDTO)
                    .toList();
            
            return ResponseEntity.ok(new ApiResponse(true, "获取分类帖子列表成功", postDTOs));
        } catch (IllegalArgumentException e) {
            // 如果分类不存在，返回错误信息
            return new ResponseEntity<>(new ApiResponse(false, "无效的分类", null), HttpStatus.BAD_REQUEST);
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updatePost(@PathVariable Long id, @RequestBody Post post) {
        if (!id.equals(post.getId())) {
            return new ResponseEntity<>(new ApiResponse(false, "ID不匹配", null), HttpStatus.BAD_REQUEST);
        }

        // 验证用户权限
        String username = ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
        User user = userService.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("User not found: " + username));

        Post existingPost = postService.getPostById(id)
                .orElseThrow(() -> new ResourceNotFoundException("帖子不存在: " + id));

        if (!existingPost.getUser().equals(user)) {
            return new ResponseEntity<>(new ApiResponse(false, "没有权限修改此帖子", null), HttpStatus.FORBIDDEN);
        }

        post.setUpdatedAt(LocalDateTime.now());
        Post updatedPost = postService.updatePost(post);
        PostDTO postDTO = ModelMapper.mapPostToDTO(updatedPost);
        return ResponseEntity.ok(new ApiResponse(true, "更新帖子成功", postDTO));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deletePost(@PathVariable Long id) {
        // 验证用户权限
        String username = ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
        User user = userService.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("User not found: " + username));

        Post existingPost = postService.getPostById(id)
                .orElseThrow(() -> new ResourceNotFoundException("帖子不存在: " + id));

        if (!existingPost.getUser().equals(user)) {
            return new ResponseEntity<>(new ApiResponse(false, "没有权限删除此帖子", null), HttpStatus.FORBIDDEN);
        }

        postService.deletePost(id);
        return ResponseEntity.ok(new ApiResponse(true, "删除帖子成功", null));
    }

    @PostMapping("/{id}/like")
    public ResponseEntity<?> likePost(@PathVariable Long id) {
        String username = ((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
        User user = userService.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("User not found: " + username));

        Post likedPost = postService.likePost(id, user);
        PostDTO postDTO = ModelMapper.mapPostToDTO(likedPost);
        return ResponseEntity.ok(new ApiResponse(true, "点赞成功", postDTO));
    }
}